package question_answer

import (
	"errors"
	"news_for_deepseek_interface/config"
	questionAnswerDto "news_for_deepseek_interface/dto/admin/question_answer"
	"news_for_deepseek_interface/model"
	tencentlke "news_for_deepseek_interface/project/tencent/lke"
	"time"

	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	tencenterrors "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	lke "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lke/v20231130"
)

func Update(params questionAnswerDto.UpdateRequest) error {

	db := model.GetInstance().GetDB()

	var questionAnswer model.QuestionAnswerModel
	if err := db.Model(&model.QuestionAnswerModel{}).Where("id = ?", params.Id).First(&questionAnswer).Error; err != nil {
		return errors.New("问答不存在")
	}

	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := lke.NewModifyQARequest()

	request.BotBizId = common.StringPtr(config.DefaultConfig.Tencent.Lke.BotBizId)
	request.QaBizId = common.StringPtr(questionAnswer.QrBizId)
	request.Question = common.StringPtr(params.Question)
	request.Answer = common.StringPtr(params.Answer)

	// 返回的resp是一个ModifyQACateResponse的实例，与请求对象对应
	_, err := tencentlke.LkeClient.ModifyQA(request)
	if _, ok := err.(*tencenterrors.TencentCloudSDKError); ok {
		return errors.New("腾讯云接口更新问答失败:" + err.Error())
	}
	if err != nil {
		return errors.New("腾讯云接口更新问答失败1:" + err.Error())
	}

	// // 发布
	// if err := tencentlke.Release(); err != nil {
	// 	return errors.New("同步腾讯云失败:" + err.Error())
	// }

	return model.GetInstance().GetDB().
		Model(&model.QuestionAnswerModel{}).
		Where("id = ?", params.Id).
		Updates(map[string]interface{}{
			"question":             params.Question,
			"answer":               params.Answer,
			"type_classify_id":     params.TypeClassifyId,
			"business_classify_id": params.BusinessClassifyId,
			"updated_at":           time.Now(),
		}).Error
}
